package com.bjzh.bjzh.servers;

import cn.hutool.json.JSONException;
import cn.hutool.json.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    /**
     * 客户端连接会触发
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("Channel active......");
    }

    /**
     * 客户端发消息会触发
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        log.info("服务器收到消息: {}", msg.toString());
//        Jtt809NettyClient.sendLocationMessage();
        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(msg);
        } catch (JSONException jsonException) {
            return;
        }
        Jtt809NettyClient.sendLocationMessage(jsonObject);
        System.err.println(jsonObject.toString());
        ctx.flush();

    }

    /**
     * 发生异常触发
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}